const address = {
  state: {
    // 缓存的发布的数据，
    unpublishedArrr:
      JSON.parse(localStorage.getItem('state'))?.address.unpublishedArrr || [],
    // 地址列表
    addressList: JSON.parse(localStorage.getItem('state'))?.address
      .addressList || [
      {
        id: '1',
        name: '张三',
        tel: '13000000000',
        address: '浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室',
        isDefault: true,
      },
      {
        id: '2',
        name: '李四',
        tel: '1310000000',
        address: '浙江省杭州市拱墅区莫干山路 50 号',
      },
    ],
    editForm: {},
    addressMsg: '', // msg 区分编辑还是新增
    chooseId:
      JSON.parse(localStorage.getItem('state'))?.address.chooseId || '1',
  },
  // 调用 mutations函数用commit
  mutations: {
    // 1. 更新编辑还是新增状态
    // update_address_msg
    updateAddressMsg(state, msg) {
      if (msg === 'add') {
        state.editForm = { name: '', address: '', addressDetail: '' }
      }
      state.addressMsg = msg
    },
    // 2. 设置默认的地址的id // set_choose_id
    SET_CHOOSE_ID(state, id) {
      state.chooseId = id
    },
    // 3. 添加用户地址 // add_address_item
    UPDATE_ADDRESS_ITEM(state, item) {
      console.log('state:', state)
      if (state.updateAddressMsg === 'add') {
        state.addressList.push({
          ...item,
          address: item.addressDetail,
          id: state.addressList.length + 1,
        })
      } else {
        state.addressList.splice(
          state.addressList.findIndex((v) => v.id === item.id),
          1,
          item
        )
      }
    },
    // 4. 设置地址管理 编辑 // set_address_item_for_edit
    SET_ADDRESS_ITEM_FOR_EDIT(state, item) {
      state.editForm = item
    },
    // 5. 设置缓存的未发布的消息 // set_unpublish_arr
    SET_UNPUBLISH_ARR(state, item) {
      state.unpublishedArrr.push(item)
    },
  },
  getters: {
    getDetaultAddress(state) {
      return state.addressList.filter((v) => v.id === state.chooseId)
    },
  },
  actions: {},
}

export default address
